package com.wash.shoes.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.google.common.collect.Lists;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.common.enums.FulFillEnum;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.domain.dy.request.DyBookRequest;
import com.wash.shoes.domain.dy.request.DyRefundRequest;
import com.wash.shoes.domain.dy.request.DyServiceUpdateRequest;
import com.wash.shoes.domain.jd.JdOrderService;
import com.wash.shoes.domain.mtbusy.MtUpdateFulFillInfo;
import com.wash.shoes.domain.vo.OrderShoeNumVo;
import com.wash.shoes.domain.washer.WasherPostService;
import com.wash.shoes.entity.*;
import com.wash.shoes.mapper.OrderGoodMapper;
import com.wash.shoes.mapper.OrderMapper;
import com.wash.shoes.mapper.OrderTransportMapper;
import com.wash.shoes.service.*;
import com.wash.shoes.util.AddressCuttingUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijianguo
 * @Date 24/10/2024 定时任务处理
 **/
@Log4j2
@Component
public class RyWashTask {

    @Resource
    ShoeService shoeService;

    @Autowired
    OrderService orderService;

    @Autowired
    ShoeRackService shakeService;

    @Autowired
    ShoeRackGridService shoeRackGridService;

    @Autowired
    CustomerCouponService customerCouponService;

    @Autowired
    WasherPostService washerPostService;

    @Autowired
    MtUpdateFulFillInfo mtUpdateFulFillInfo;

    @Resource
    RegionTransactionDetailService regionTransactionDetailService;

    @Resource
    RegionDistributorService regionDistributorService;

    @Autowired
    OrderGoodService orderGoodService;
    @Autowired
    private FactoryshelvesRackGridService factoryshelvesRackGridService;
    @Autowired
    private FactoryShelvesService factoryShelvesService;


    @Autowired
    OrderTransportService orderTransportService;

    @Autowired
    JdOrderService jdOrderService;


    @Autowired
    DyRefundRequest dyRefundRequest;

    @Autowired
    ShopService shopService;

    @Autowired
    DyServiceUpdateRequest dyServiceUpdateRequest;

    /**
     * 暂时测试可以分账的品牌为：海马洗护
     */
    private static List<String> brandList = new ArrayList<>();

    static {
        brandList.add("202509106521326476");
    }


    /**
     * @author lijianguo
     * @Date 24/10/2024 鞋子自动出库 定时任务
     **/
    public void washShoeOut() {
        log.info("鞋子自动出库 定时任务......");
        // 获取清洗清洗中的鞋子
        List<ShoePo> shoePoList = shoeService.getWashShoe();
        // 循环处理
        for (ShoePo shoePo : shoePoList) {
            // 如果是反洗的鞋子，就不需要处理
            if (StrUtil.isNotEmpty(shoePo.getExtendInfo())) {
                continue;
            }

            OrderPo orderPo = orderService.getById(shoePo.getOrderId());
            if (Objects.isNull(orderPo)) {
                log.info("自动出库找不到对应订单，订单ID {} ", shoePo.getOrderId());
                continue;
            }

            List<OrderGoodPo> orderGoods = orderGoodService.getOrderGoods(orderPo.getId());
            // 商品名称
            String goodsName = orderGoods.stream().findFirst().orElse(new OrderGoodPo()).getName();
            boolean flag = AddressCuttingUtil.isGoodsName(goodsName);
            if (flag) {
                // 不是全部为鞋子的单子不走自动出库
                continue;
            }

            // 如果是推送到工厂订单就不需要自动出库
            if (StringUtils.isNotBlank(shoePo.getWashShop()) && StringUtils.isNotBlank(orderPo.getWashShop())
                    && orderPo.getStatus() == 3) {
                continue;
            }

            List<ShoePo> shoeOrderPoList = shoeService.orderNotWashShoe(shoePo.getOrderId(), shoePo.getId());
            // 所有的鞋子清洗完成, 待出库
            if (shoeOrderPoList.isEmpty()) {
                orderPo.setStatus(OrderStatusEnum.PENDING_OUTBOUND.getStatus());
                orderService.updateById(orderPo);
            }
            // 鞋子清洗完成
            shoePo.setStatus(2);
            // 释放鞋架
            /*  ShoeRackGridPo shoeRackGridPo = shoeRackGridService.getByShoeId(shoePo.getId());
            if (shoeRackGridPo != null) {
                shoeRackGridPo.setShoeId(null);
                shoeRackGridService.updateById(shoeRackGridPo);
                log.info("释放鞋架 {} ", shoeRackGridPo.getShowCode());
            }*/
            shoeService.updateById(shoePo);
            if (StringUtils.isEmpty(shoePo.getOrderId())) {
                return;
            }
            // 计算鞋架的鞋子使用数量
            List<FactoryshelvesRackGridPo> data =
                    factoryshelvesRackGridService.list(new LambdaQueryWrapper<FactoryshelvesRackGridPo>()
                            .eq(FactoryshelvesRackGridPo::getOrderId, shoePo.getOrderId()));
            if (CollectionUtil.isEmpty(data)) {
                return;
            }
            FactoryshelvesRackGridPo factoryshelvesRackGridPo = data.get(0);

            // 设置格子的订单为null
            SpringUtil.getBean(RyWashTask.class).updateFactoryShevelsOrderId(factoryshelvesRackGridPo);
            // 修改货架的已使用数量
            factoryShelvesService.updateUseNumInteger(factoryshelvesRackGridPo.getFactoryshelvesId());

        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean updateFactoryShevelsOrderId(FactoryshelvesRackGridPo factoryshelvesRackGridPo) {
        factoryshelvesRackGridPo.setOrderId(null);
        // factoryshelvesRackGridService.updateById(factoryshelvesRackGridPo);
        int falg = factoryshelvesRackGridService.updateFactoryShevelsOrderIdWithId(factoryshelvesRackGridPo.getId());
        log.info("释放货架绑定的订单id:{},falg:{}", factoryshelvesRackGridPo.getFactoryshelvesId(), falg);
        return SqlHelper.retBool(falg);
    }

    /**
     * @author lijianguo
     * @Date 29/10/2024 计算使用的货架数量
     **/
    public void countRackUserNums() {

        List<ShoeRackPo> dataList = shakeService.getAllRackList();
        for (ShoeRackPo shoeRackPo : dataList) {
            shakeService.updateUseNumInteger(shoeRackPo.getId());
        }

    }

    /**
     * 取消订单
     */
    public void cancelPayOrder() {

        List<OrderPo> orderPos = orderService.getNotPayOrder();
        for (OrderPo orderPo : orderPos) {
            if (DateUtil.betweenMs(DateUtil.date(), orderPo.getCreateTime()) > 3600 * 1000) {
                orderPo = orderService.getById(orderPo.getId());
                if (Objects.equals(orderPo.getStatus(), OrderStatusEnum.PRE_PAY.getStatus())) {
                    // 自动取消订单
                    orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());
                    orderService.updateById(orderPo);
                    // 归还优惠卷
                    CustomerCouponPo customerCouponPo = customerCouponService.getByOrderId(orderPo.getId());
                    if (customerCouponPo != null) {
                        customerCouponPo.setStatus(0);
                        customerCouponPo.setUserTime(null);
                        customerCouponService.updateById(customerCouponPo);
                    }
                }
                // 这里需要取消订单对应的推广信息,
                regionTransactionDetailService.cancelTransaction(orderPo.getId());
            }
        }
    }

    /**
     * 推送订单,shop清洗中以及店铺配置了的
     */
    public void pushOrder() {
        //自动化工厂目前只推送订单在新津工厂地址洗的订单
        List<OrderPo> orderPos = orderService.needPushOrder();
        if (CollectionUtil.isEmpty(orderPos)) {
            return;
        }
        for (OrderPo orderPo : orderPos) {
            washerPostService.sendToMachine(orderPo);
        }
    }

    /**
     * 美团的订单的完成
     */
    public void mtFullFillOrder() {
        List<OrderPo> orderPoList = orderService.getMtNotFullFillOrderList();
        for (OrderPo orderPo : orderPoList) {
            ShopPo shopPo = shopService.getById(orderPo.getShopId());
            //TODO DeveloperId=114769 美团梵尘洗护现在已经没有卖了，鉴权失败 这里先过滤一下
            if (Objects.nonNull(shopPo) && StringUtils.equals(shopPo.getDeveloperId(), "114769")) {
                log.info("developerId=114769 的订单，orderId={}", orderPo.getId());
                continue;
            }
            FulFillEnum fulFillEnum = mtUpdateFulFillInfo.getMtOrderStatus(orderPo);
            orderPo.setFulfillStatus(fulFillEnum.getCode());
            orderService.updateById(orderPo);
            if (FulFillEnum.COMPLETION.equals(fulFillEnum)) {
                log.info(orderPo.toString());
                continue;
            }
            // 处理为已经完成
            mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.COMPLETION, "刷鞋匠", "13892920924");
        }
    }

    /**
     * 处理分销商的结算
     */
    public void distributorSettlement() {
        List<RegionTransactionDetailPo> dataList = regionTransactionDetailService.getUniFinishDis();
        // 如果这个数据
        for (RegionTransactionDetailPo regionTransactionDetailPo : dataList) {
            RegionDistributorPo regionDistributorPo =
                    regionDistributorService.getByUserId(regionTransactionDetailPo.getRecommendId());
            // 添加订单的数量+1 添加收益的数量
            regionDistributorPo.setPromotionOrderNum(regionDistributorPo.getPromotionOrderNum() + 1);
            regionDistributorPo.setPromotionProfit(
                    regionDistributorPo.getPromotionProfit() + regionTransactionDetailPo.getPromotionProfit());
            regionDistributorService.updateById(regionDistributorPo);
            // 设置已经处理入账了
            regionTransactionDetailPo.setStatus(1);
            regionTransactionDetailService.updateById(regionTransactionDetailPo);
        }
    }


    /**
     * 抖音已经完成核销 可以分账的单子
     */
    public void dyVerification() {
        //查询抖音已经完成核销，可以分账订单
        List<OrderPo> list = orderService.queryDyVerification();

        //过滤出可以分账的品牌
        List<OrderPo> result = Optional.ofNullable(list)
                .orElse(Lists.newArrayList())
                .stream()
                .filter(orderPo -> brandList.contains(orderPo.getBrandId()))
                .collect(Collectors.toList());

        //从抖音获取每个核销单子金额

        //拿取分账比例，暂时写死

        //调用抖音发起分账


    }

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderTransportMapper orderTransportMapper;
    @Autowired
    private DyBookRequest dyBookRequest;

    /**
     * 预约中状态
     */
    private static final String BOOKING = "BOOKING";
    @Autowired
    private OrderGoodMapper orderGoodMapper;

    /**
     * 查询抖音预约单子为预约中状态的,就去调用确认接单
     */
    public void dyAutoBooking() {
        //抖音渠道并且是取鞋中的并且预约成功没有被接单的
        List<OrderPo> orderPos = orderMapper.selectList(new LambdaQueryWrapper<OrderPo>().eq(OrderPo::getComeFrom, "3")
                .eq(OrderPo::getStatus, OrderStatusEnum.PICK_UP_SHOES.getStatus()).and(e -> {
                    e.eq(OrderPo::getAccepted, false).or().isNull(OrderPo::getAccepted);
                })
                .gt(OrderPo::getCreateTime, DateUtil.parse("2025-09-18 00:00:00", "yyyy-MM-dd HH:mm:ss"))
                .orderByDesc(OrderPo::getCreateTime).last("limit 5"));
        // 查询物流
        if (CollectionUtil.isNotEmpty(orderPos)) {
            orderPos.forEach(e -> {
                OrderTransportPo orderTransportPo = orderTransportMapper.getOneByOrderIdType(e.getId(), "取鞋");
                //如果物流单不为空,并且抖音预约单创建成功,就去查询预约单
                if (Objects.nonNull(orderTransportPo) && Objects.nonNull(e.getDyBookId())) {
                    List<OrderGoodPo> data = orderGoodMapper.selectList(new LambdaQueryWrapper<OrderGoodPo>().eq(OrderGoodPo::getOrderId, e.getId()));
                    if (CollectionUtil.isNotEmpty(data)) {
                        data.stream().forEach(orderGoodPo -> {
                            // BOOKING 预约中 SUCCESS 预约成功 FINISH 预约完成(已核销） CANCEL 预约取消 FAIL 预约失败
                            String status = dyBookRequest.queryBook(e, orderGoodPo);
                            log.info("dy book query,orderId:{} status:{}", e.getId(), status);
                            if (BOOKING.equals(status)) {
                                //调用预约接单接口
                                boolean flag = dyBookRequest.bookResultCallback(e, orderGoodPo);
                                log.info("dy book result callback,orderId:{} flag:{},orderNo:{}", e.getId(), flag, e.getOrderNo());
                                orderGoodPo.setAccepted(flag);
                                orderGoodMapper.updateById(orderGoodPo);
                            }
                            if (StringUtils.equals(status, "SUCCESS") || StringUtils.equals(status, "FINISH")) {

                                orderGoodPo.setAccepted(true);
                                orderGoodMapper.updateById(orderGoodPo);
                                long count = orderGoodMapper.selectCount(new LambdaQueryWrapper<OrderGoodPo>().eq(OrderGoodPo::getOrderId, e.getId()));
                                //订单的数量等于已接单的数量
                                if (count == orderGoodMapper.selectCount(new LambdaQueryWrapper<OrderGoodPo>().eq(OrderGoodPo::getOrderId, e.getId()).eq(OrderGoodPo::getAccepted, true))) {
                                    //调用预约接单接口
                                    log.info("dy book result callback,orderId:{} flag:{},orderNo:{}", e.getId(), true, e.getOrderNo());
                                    e.setAccepted(true);
                                    orderMapper.updateById(e);
                                }
                            }
                            if (StringUtils.equals(status, "CANCEL") || StringUtils.equals(status, "FAIL")) {

                                //检查是否退款
                                String refundStatus = dyRefundRequest.queryRefund(e);
                                if ("SUCCESS".equals(refundStatus)) {
                                    //退款成功就取消物流
                                    if (!StringUtils.equals(orderTransportPo.getStatus(), "690")) {
                                        //调用物流取消
                                        jdOrderService.cancelJdOrder(orderTransportPo.getWayBillCode());
                                        //更新物流表
                                        orderTransportPo.setStatus("690");
                                        orderTransportService.updateById(orderTransportPo);

                                        //更新订单表
                                        e.setAccepted(true);
                                        e.setStatus(OrderStatusEnum.CANCEL.getStatus());
                                        orderMapper.updateById(e);
                                    }
                                }
                            }
                        });
                    }
                }
            });
        }
    }


    /**
     * 查询抖音未核销订单，如果未核销就去调用核销接口核销
     */
    public void dyCheckVerification() {
        List<OrderPo> orderPos = orderMapper.selectList(
                new LambdaQueryWrapper<OrderPo>()
                        .eq(OrderPo::getComeFrom, "3")
                        .in(OrderPo::getStatus, 3, 4, 5, 6)
                        .gt(OrderPo::getCreateTime, DateUtil.parse("2025-09-23 00:00:00", "yyyy-MM-dd HH:mm:ss"))
                        .isNull(OrderPo::getDyVerificationTime)
                        .orderByDesc(OrderPo::getCreateTime)
                        .last("limit 5")
        );
        if (CollectionUtil.isNotEmpty(orderPos)) {
            orderPos.forEach(e -> {
                log.info("dy dyCheckVerification result callback,orderId:{},status:{}", e.getId(), e.getStatus());
                dyServiceUpdateRequest.updateFullFill(e, 4);
            });
        }
    }

    /**
     * 定时更新每天的入库数据,纠正订单order表上的shoeNum字段为实际入库的订单对应的shoe表的实际条数
     */
    public void correctOrderShoeNum() {
        //查询当天鞋子表入库的数据
//        SELECT DISTINCT order_id,count(1) as showNum from os_shoe where DATE(storage_time)='2025-10-20' GROUP BY order_id
        List<OrderShoeNumVo> orderShoeNumVos = orderMapper.getOrderShoeNum(DateUtil.format(new Date(), "yyyy-MM-dd"));
        if (CollectionUtil.isNotEmpty(orderShoeNumVos)) {
            orderShoeNumVos.forEach(e -> {
                //查询订单表
                OrderPo orderPo = orderMapper.selectById(e.getOrderId());
                if (Objects.nonNull(orderPo) && !Objects.equals(e.getShoeNum(), orderPo.getShoeNum())) {
                    //更新订单表
                    orderPo.setShoeNum(e.getShoeNum());
                    orderMapper.updateById(orderPo);
                }
            });
        }
    }
}
